package com.gitee.leijin.rbac.security.handler;

import cn.hutool.json.JSONUtil;
import com.gitee.leijin.rbac.security.SecurityUser;
import com.gitee.leijin.rbac.service.CacheManager;
import com.gitee.leijin.rbac.util.AjaxUtils;
import com.gitee.leijin.rbac.util.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SuccessLogoutHandler implements LogoutHandler {

    @Resource
    private CacheManager cacheManager;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUser) {
            SecurityUser securityUser = (SecurityUser) principal;

            // 退出登录时删除用户在redis中的token信息
            cacheManager.del(String.valueOf(securityUser.getSysUser().getUserId()));

            // SecurityContextPersistenceFilter 此filter会清除Context
            //SecurityContextHolder.clearContext();

            Result<String> logoutResult = Result.success("注销成功");
            AjaxUtils.response(response, JSONUtil.toJsonStr(logoutResult));
        }
    }
}
